import router from "../router";
import axios from "axios";
import { useMessage } from "naive-ui";
import { useRouter } from "vue-router";
import dxPeer from "../store/dxPeer";
import { apiUrl } from "./config";
let prefix = apiUrl;
import icon from "naive-ui/lib/_internal/icon";

export const outInt = () => {
  localStorage.clear();
  // localStorage.removeItem("token")

  router.push({
    path: "login",
  });
  try {
    dxPeer.commit("destroy");
  } catch (e) { }
};

//  let prefix = "http://127.0.0.1:8360/";
/**
 * 格式化日期
 * @param t 时间戳
 * @returns
 */
export const prefixS = prefix;
export function transferTimeYMDHm(t?) {
  const time = new Date();
  time.setTime(t ? t : new Date().getTime());
  const Year = time.getFullYear(),
    Month = time.getMonth() + 1,
    Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate(),
    hour = time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
    Minutes =
      time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes(),
    Seconds =
      time.getSeconds() < 10 ? 0 + "" + time.getSeconds() : time.getSeconds();
  return `${Year}-${Month}-${Data} ${hour}:${Minutes}`;
}
export function transferTimeseer(t?) {
  const time = new Date(t);
  const Year = time.getFullYear(),
    Month = time.getMonth() + 1,
    Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate(),
    hour = time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
    Minutes =
      time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes(),
    Seconds =
      time.getSeconds() < 10 ? 0 + "" + time.getSeconds() : time.getSeconds();
  return `${Year}年${Month}月${Data}日`;
}
export function transferTimeYMDHmxqer(t?) {
  const time = new Date();
  time.setTime(t ? t : new Date().getTime());
  let Year = time.getFullYear(),
    Month = time.getMonth() + 1,
    Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate()
  if (Month < 10) {
    Month = '0' + Month
  }

  return `${Year}${Month}${Data}`;
}



export function transferTimeYMD(t: any) {
  t = parseInt(t);
  const time = new Date(t ? t : new Date().getTime());
  let Year = time.getFullYear(),
    Month = time.getMonth() + 1,
    Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate();
  Month = Month < 10 ? '0' + Month : Month
  return `${Year}-${Month}-${Data}`;
}
export function transferTimeYMDSting(t: string) {
  const time = new Date(t);
  let Year = time.getFullYear(),
    Month = time.getMonth() + 1,
    Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate();

  Month = Month < 10 ? '0' + Month : Month
  return `${Year}-${Month}-${Data}`;
}
export function transferHm(t) {
  const time = new Date();
  time.setTime(t);
  const hour =
    time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
    Minutes =
      time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes();
  return `${hour}:${Minutes}`;
}
export function setTimes(da) {
  const time = new Date(parseInt(da));
  time.setHours(0);
  time.setMinutes(0);
  time.setSeconds(0);
  return time.getTime();
}

export const isToday = (str) => {
  return new Date().getTime() - new Date(parseInt(str)).getTime() < 86400000;
};

/**
 * 路由跳转
 * @param url 跳转地址
 * @param cu 额外的参数
 */
export function hf(url: string, cu?: any) {
  const jhher = {}
  if (url.indexOf("?") >= 0) {
    const jjnherr = url.split("?")[1]
    jhher[jjnherr.split("=")[0]] = jjnherr.split("=")[1].split("&")[0]
    cu = jhher
  }
  router.push({
    path: url,
    query: cu,
  });
}
/**
 * post请求111
 * @param url  接口地址
 * @param data 参数
 * @returns
 */
export function dxpost(url: string, data: any, method?: any) {
  const message = useMessage();
  if (!data) {
    data = {};
  }
  data = JSON.parse(JSON.stringify(data));
  if (!data["id"]) {
    delete data["id"];
  }
  try {
    for (let key in data) {
      if (data[key] instanceof Array) {
        data[key] = data[key].join(",");
      }
    }
  } catch (e) { }
  let urls = prefix + url
  if (url.indexOf("http") >= 0) {
    urls = url;
  }
  data.update_by = localStorage.Userid
  data.create_by = localStorage.Userid


  // for (let key in data) {
  //   if (data[key] === "null" || data[key] === "") {
  //     delete data[key];
  //   }
  // }
  return new Promise((resolve) => {
    axios({
      method: method || "post",
      url: urls,
      headers: {
        token: localStorage.token,
        apptoken:localStorage.app_auth_token,
          ipid:localStorage.ip_role_id
      },
      data: data,
    })
      .then((res) => {
        if (res.data.errno != 0) {
          window.$message.destroyAll();
          window.$message.error(res.data.errmsg);
        }
        if (res.data.errno == -2) {
          outInt();
          return;
        }
        resolve(res.data);
      })
      .catch((res) => {
        const ress = "" + res;
        window.$message.destroyAll();
        window.$message.error(res.errmsg);
        console.log("错误");
      });
  });
}

/**
 * get请求
 * @param url 接口地址
 * @param data 参数
 * @returns
 */
export function dxget(url: string, data?: any) {
  let urls = prefix + url;
  if (url.indexOf("http") >= 0) {
    urls = url;
  }
  if (data) {
    data = JSON.parse(JSON.stringify(data));
  }
  for (let key in data) {
    if (data[key] === "null" || data[key] === "") {
      delete data[key];
    }
    if (key == "TheTime") {
      data[key] = parseInt(data[key] / 100000000);
    }
  }
 
  return new Promise((resolve) => {
    axios
      .get(urls, {
        params: data,
        headers: {
          token: localStorage.token,
          apptoken:localStorage.app_auth_token,
          ipid:localStorage.ip_role_id
        },
      })
      .then(async function (response) {
        if (response.data.errno != 0) {
          window.$message.destroyAll();
          window.$message.error(response.data.errmsg);
        }
        if (response.data.errno == -2) {
          outInt();
          return;
        }
        resolve(response.data);
      })
      .catch((res) => {
        const ress = "" + res;
        window.$message.destroyAll();
        window.$message.error(res.errmsg);
        return;
        resolve(ress);
      });
  });
}


/**
 * get请求
 * @param url 接口地址
 * @param data 参数
 * @returns
 */
export function dxgetchat(url: string, headers?, data?: any) {

  return new Promise((resolve) => {
    axios
      .get(url, {
        params: data,
        headers,
      })
      .then(async function (response) {
        resolve(response.data);
      })
      .catch((res) => {
        resolve(res);
      });
  });
}

export function dxchatapi(url: string, data: any, method?: any) {
  return new Promise((resolve) => {
    axios({
      method: method || "post",
      url: url,
      headers: {
        "Content-Type": "application/json",
        Authorization: 'Bearer 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'
      },
      data: data,
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((res) => {
        console.log("错误");
      });
  });
}



/**
 * del
 * @param url 接口地址
 * @param data 参数
 * @returns
 */
export function dxdel(url: string, data: any) {
  window.$message.destroyAll();
  let urls = prefix + url;
  if (url.indexOf("http") >= 0) {
    urls = url;
  }
  return new Promise((resolve) => {
    axios
      .delete(urls, {
        params: data,
        headers: {
          token: localStorage.token,
        },
      })
      .then(function (response) {
        if (response.data.errno != 0) {
          window.$message.error(response.data.errmsg);
        }
        if (response.data.errno == -2) {
          outInt();
          return;
        }
        resolve(response.data);
      })
      .catch((res) => {
        const ress = "" + res;
        window.$message.error(res.errmsg);
        resolve(ress);
      });
  });
}

/**
 * 逗号金额转金额
 * @param buyTotal 带逗号的金额 如 10,000,000
 * @returns
 */
export function CommaTransferAmount(buyTotal) {
  try {
    const jiner = parseFloat(buyTotal.replace(new RegExp(",", "g"), ""));
    return (jiner / 100000000).toFixed(2);
  } catch (e) {
    return '--'
  }
}

/**
 * 滚动到底部监听
 * @param className  class名称
 * @param fun 滚动到底部的回调方法
 */
export function bottomMonitor(className, fun) {
  new IntersectionObserver((entries) => {
    let item = entries[0]; // 拿第一个就行，反正只有一个
    if (item.isIntersecting) {
      fun();
      console.log("滚动到了底部，开始请求数据");
    }
  }).observe(document.querySelector("." + className)); // 监听参照元素
}
/**
 * 获取路由后面的参数
 * @returns
 */
export const qurl = () => {
  const { currentRoute } = useRouter();
  const qurl = currentRoute.value.query;
  return qurl;
};
// 返回上一页
export const callBack = () => {
  router.go(-1);
};
/**
 * 股票代码转换
 * @param code 股票代码
 * @returns
 */
export function getCodesd(code) {
  const colum = "" + code.substr(0, 3);
  let text = 0;
  switch (colum) {
    case "000":
    case "001":
    case "002":
    case "003":
    case "300":
    case "301":
      text = 0;
      break;
    case "600":
    case "601":
    case "603":
    case "605":
    case "688":
      text = 1;
      break;
  }
  return text + "." + code;
}

export function getCodesder(code) {
  const colum = "" + code.substr(0, 3);
  let text = "";
  switch (colum) {
    case "000":
    case "001":
    case "002":
    case "003":
    case "300":
    case "301":
      text = "SZ";
      break;
    case "600":
    case "601":
    case "603":
    case "605":
    case "688":
      text = "SH";
      break;
  }
  return code + "." + text;
}

/**
 * 金额转换成 亿单位
 * @param val
 * @returns
 */
export const MU = (val) => {
  let fixexs = (val / 100000000).toFixed(2);
  if (fixexs == "NaN") {
    fixexs = "-";
  }
  return fixexs + "亿";
};
/**
 * 保留两位小数
 * @param val
 * @returns
 */
export const toFixed = (val) => {
  const xkje = parseFloat(val)
  return xkje.toFixed(2);
};
/**
 * 金额转换成万单位
 * @param val
 * @returns
 */
export const AU = (val) => {
  let fixexs = (val / 10000).toFixed(2);
  if (fixexs == "NaN") {
    fixexs = "-";
  }
  return fixexs + "万";
};
/**
 * 设置颜色  条件为真显示红色
 */
export const setColour = (val) => {
  return val ? "red" : "ls";
};
// 提交弹出确认取消框弹框
export const dialog = (content) => {
  return new Promise((resolve) => {
    window.$useDialog.warning({
      title: "警告",
      content: content,
      positiveText: "确定",
      negativeText: "取消",
      onPositiveClick: () => {
        resolve(1);
      },
    });
  });
};

/**
 * 添加到观察区
 * @param scode  股票代码
 * @param laiyuan  来源
 * @param text 额外参数 json格式的字符串
 */
export const addGuanca = async (scode, laiyuan, text) => {
  /*获取诊断结果*/
  // const jhbjse = [];
  // const stockdiagnosis: any = await dxget("dc/stockdiagnosis", {
  //   code: scode,
  //   type: 1,
  // });
  // jhbjse.push(stockdiagnosis.data);

  // const stockdiagnosisbb: any = await dxget("dc/stockdiagnosis", {
  //   code: scode,
  //   type: 2,
  // });
  // jhbjse.push(stockdiagnosisbb.data);

  // const stockdiagnosiscc: any = await dxget("dc/stockdiagnosis", {
  //   code: scode,
  //   type: 3,
  // });
  // jhbjse.push(stockdiagnosiscc.data);

  // const stockdiagnosisdd: any = await dxget("dc/stockdiagnosis", {
  //   code: scode,
  //   type: 4,
  // });
  // jhbjse.push(stockdiagnosisdd.data);
  /*end*/

  const resData: any = await dxget("gupiao/getJiage", {
    scode: scode,
  });
  const res = {
    observetype: "",
    code: "" + scode,
    name: resData.data.f58,
    parameter: JSON.stringify(text),
    record: JSON.stringify({
      secCode: resData.data.f57,
      price: resData.data.f19,
      announcementTime: new Date().getTime(),
      laiyuan: laiyuan,
      extra: JSON.stringify(resData.data),
    }),
  };
  if (text.observetype) {
    res.observetype = text.observetype;
  }
  const { errno, data }: any = await dxpost("gupiao/addCode", res);
  if (errno == 0) {
    window.$message.success(data.msgText);
  }
};

export const handleDate = (dateTimeStamp) => {
  var result = "";
  var now = new Date().getTime();
  var diffValue = now - dateTimeStamp;
  let jnhgweM = diffValue / 1000;
  let jnhgwe = diffValue / (60 * 1000);
  let jnhgweb = diffValue / (60 * 1000 * 60);
  jnhgwe = parseInt("" + jnhgwe);
  let StrDate = "";
  if (jnhgweM < 20) {
    StrDate = "刚刚";
  } else if (jnhgwe < 20) {
    StrDate = jnhgwe + 1 + "分钟前";
  } else if (jnhgweb < 24) {
    StrDate = transferHm(dateTimeStamp);
  } else {
    StrDate = transferTimeYMDHm(dateTimeStamp);
  }
  return StrDate;
};


export const timeago = (dateTimeStamp) => {
  var minute = 1000 * 60;      //把分，时，天，周，半个月，一个月用毫秒表示
  var hour = minute * 60;
  var day = hour * 24;
  var week = day * 7;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();   //获取当前时间毫秒
  console.log(now)
  var diffValue = now - dateTimeStamp;//时间差

  if (diffValue < 0) {
    return;
  }
  var minC = diffValue / minute;  //计算时间差的分，时，天，周，月
  var hourC = diffValue / hour;
  var dayC = diffValue / day;
  var weekC = diffValue / week;
  var monthC = diffValue / month;
  let result = ""
  if (monthC >= 1 && monthC <= 3) {
    result = " " + parseInt(monthC) + "月"
  } else if (weekC >= 1 && weekC <= 3) {
    result = " " + parseInt(weekC) + "周"
  } else if (dayC >= 1 && dayC <= 6) {
    result = " " + parseInt(dayC) + "天"
  } else if (hourC >= 1 && hourC <= 23) {
    result = " " + parseInt(hourC) + "小时"
  } else if (minC >= 1 && minC <= 59) {
    result = " " + parseInt(minC) + "分钟"
  } else if (diffValue >= 0 && diffValue <= minute) {
    result = "刚刚"
  } else {
    var datetime = new Date();
    datetime.setTime(dateTimeStamp);
    var Nyear = datetime.getFullYear();
    var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
    var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
    var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
    result = Nyear + "-" + Nmonth + "-" + Ndate
  }
  return result;
}


// 表情加码
export const utf16toEntities = (str) => {
  const patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
  str = str.replace(patt, (char) => {
    let H;
    let L;
    let code;
    let s;

    if (char.length === 2) {
      H = char.charCodeAt(0); // 取出高位
      L = char.charCodeAt(1); // 取出低位
      code = (H - 0xd800) * 0x400 + 0x10000 + L - 0xdc00; // 转换算法
      s = `&#${code};`;
    } else {
      s = char;
    }

    return s;
  });

  return str;
};
// 表情解码
export const entitiestoUtf16 = (strObj) => {
  if (!strObj) {
    return;
  }
  const patt = /&#\d+;/g;
  const arr = strObj.match(patt) || [];

  let H;
  let L;
  let code;

  for (let i = 0; i < arr.length; i += 1) {
    code = arr[i];
    code = code.replace("&#", "").replace(";", "");
    // 高位
    H = Math.floor((code - 0x10000) / 0x400) + 0xd800;
    // 低位
    L = ((code - 0x10000) % 0x400) + 0xdc00;
    code = `&#${code};`;
    const s = String.fromCharCode(H, L);
    strObj = strObj.replace(code, s);
  }
  return strObj;
};

export const ISimg = (strObj) => {
  if (!strObj) {
    return false;
  }
  if (strObj.indexOf("jpg") > -1 || strObj.indexOf("png") > -1) {
    return "[图片]";
  }
};
// 验证手机号
export const yzphone = (a) => {
  var b = !1;
  return (
    a.match(
      /^13[0-9]{9}|15[0-9]{9}|14[0-9]{9}|19[0-9]{9}|16[0-9]{9}|17[0-9]{9}|18[0-9]{9}$/
    ) &&
    11 == a.length &&
    (b = !0),
    b
  );
};
/*格式化路由*/
export const routeSwitch = (data: any) => {
  const stair = [];
  data.map((a) => {
    const objT: any = a;
    if (a.parentMenuCode == 0) {
      objT.id = a.id;
      objT.icon = a.icon;
      objT.name = a.title;
      objT.jurisdiction = [
        {
          name: a.PagePermissionIdentification,
          text: "页面",
        },
      ];
      objT.children = [];
      stair.push(objT);
    }
  });
  stair.map((a) => {
    data.map((b) => {
      if (a.id == b.parentMenuCode) {
        const obj = {
          ...b,
          id: b.id,
          isshow: true,
          name: b.title,
          url: b.chainedAddress,
          jurisdiction: [
            {
              name: b.PagePermissionIdentification,
              text: "页面",
            },
            {
              name: b.DeletePermissionID,
              text: "删除",
            },
            {
              name: b.ViewPermissionID,
              text: "查看",
            },
            {
              name: b.EditPermissionIdentifier,
              text: "编辑",
            },
            {
              name: b.NewPermissionIdentifier,
              text: "新增",
            },
          ],
        };
        a.children.push(obj);
      }
    });
  });
  return stair;
};

export const iconData = [
  "dx-guaduan",
  "dx-jieting",
  "dx-dianhua",
  "dx-shipin",
  "dx-xiaolian",
  "dx-tupian1",
  "dx-yejian",
  "dx-ziyuan",
  "dx-weixin",
  "dx-shuaxin1",
  "dx-sousuo",
  "dx-xiala",
  "dx-zhifubaozhifu",
  "dx-tongzhi",
  "dx-youjiantou",
  "dx-shezhi1",
  "dx-github-fill",
  "dx-facebook-fill",
  "dx-suoxiao",
  "dx-fangda",
  "dx-zuojiantou",
  "dx-zhongyingwenyingwen-01",
  "dx-closefill",
  "dx-shezhi",
  "dx-attachment",
  "dx-edit",
  "dx-eye-close",
  "dx-email",
  "dx-file-common",
  "dx-fullscreen-shrink",
  "dx-fullscreen-expand",
  "dx-map",
  "dx-help",
  "dx-modular",
  "dx-pin",
  "dx-save",
  "dx-search",
  "dx-scanning",
  "dx-shuaxin",
  "dx-tupian",
  "dx-wenbenbianji",
  "dx-shanchu",
  "dx-huodong",
  "dx-admin-manage",
  "dx-gupiao-shouye",
  "dx-user",
  "dx-reduce",
  "dx-bianjiwenzhang_huaban",
  "dx-add",
  "dx-zhankaicaidan",
  "dx-shijian",
  "dx-shouqicaidan",
  "dx-close",
  "dx-right",
  "dx-left",
  "dx-toleft",
  "dx-caidan_o",
  "dx-gouxuan",
  "dx-arrow-down",
];

//   康盛的默认产品编码  ks2022070240001 格式

export const kscpbm = async () => {
  const time = new Date();
  let Year = time.getFullYear(),
    Month = time.getMonth() + 1,
    MonthS = null,
    Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate();
  if (Month < 10) {
    MonthS = "0" + Month;
  } else {
    MonthS = Month;
  }
  let strs = `ks${Year}${MonthS}${Data}`;
  const { data }: any = await dxget("ks/index/getCpbmlength", {
    productCode: strs,
  });
  let jhbj = "";
  if (data < 1000) {
    jhbj = "0" + (data + 1);
  }
  if (data < 100) {
    jhbj = "00" + (data + 1);
  }
  if (data < 10) {
    jhbj = "000" + (data + 1);
  }
  return strs + jhbj;
};

// 动态加载js
export const dynamicLoadJs = (url, callback?) => {
  var head = document.getElementsByTagName("head")[0];
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = url;
  if (typeof callback == "function") {
    script.onload = script.onreadystatechange = function () {
      if (
        !this.readyState ||
        this.readyState === "loaded" ||
        this.readyState === "complete"
      ) {
        callback();
        script.onload = script.onreadystatechange = null;
      }
    };
  }
  head.appendChild(script);
};

export const fontStle = (data) => {
  const styleObj = {
    top: data.y + "px",
    left: data.x + "px",
    width: data.w + "px",
    height: data.h + "px",
    fontSize: data.fontSize + "px",
    lineHeight: data.lineHeight + "px",
    fontWeight: data.isBlod ? 600 : 100,
    color: data.colorVal,
    backgroundColor: data.backgroundColor,
    paddingTop: data.paddingT + "px",
    paddingRight: data.paddingR + "px",
    paddingBottom: data.paddingB + "px",
    paddingLeft: data.paddingL + "px",
    textAlign: data.textAlign,
  };
  if (data.border) {
    data.border.map(a => {
      if (a == 1) {
        styleObj['borderTop'] = "1px solid #000"
      }
      if (a == 2) {
        styleObj['borderBottom'] = "1px solid #000"
      }
      if (a == 3) {
        styleObj['borderLeft'] = "1px solid #000"
      }
      if (a == 4) {
        styleObj['borderRight'] = "1px solid #000"
      }
    })
  }
  return styleObj;
};

export const ImgStle = (data) => {
  const styleObj = {
    top: data.y + "px",
    left: data.x + "px",
    width: data.w + "px",
    height: data.h + "px",
    objectFit: data.imgXsVal,
    borderRadius: data.ImagesRoundedCorners + "px",
  };
  if (data.border) {
    data.border.map(a => {
      if (a == 1) {
        styleObj['borderTop'] = "1px solid #000"
      }
      if (a == 2) {
        styleObj['borderBottom'] = "1px solid #000"
      }
      if (a == 3) {
        styleObj['borderLeft'] = "1px solid #000"
      }
      if (a == 4) {
        styleObj['borderRight'] = "1px solid #000"
      }
    })
  }
  return styleObj;
};
export const checkboxtle = (data) => {
  const styleObj = {
    fontSize: data.fontSize + "px",
    lineHeight: data.lineHeight + "px",
    fontWeight: data.isBlod ? 600 : 100,
    color: data.colorVal,
  };
  return styleObj;
};
export const Imgbanner = (data) => {
  const styleObj = {
    objectFit: data.imgXsVal,
  };
  return styleObj;
};

/**
 * 导出
 * @param file  导入的文件
 * @param jhbjhwe 导入的json格式如
 * [
    {
      name: "编号",
      key: "serialNumber",
    },
    {
      name: "序号",
      key: "numericalOrder",
    },
    {
      name: "描述",
      key: "describe",
    },
  ]
 * @param url  导入的接口地址
 * @param name  数据库名称
 * @param ew  额外的参数
 * @param drerrtext 导入失败的提示
 * @param sjname 数据库名称
 * @returns 
 */
export const readExcel = (file, jhbjhwe, name, ew, drerrtext, sjname, ewcsobj) => {
  // 解析Excel
  return new Promise(function (resolve) {
    // 返回Promise对象
    const reader = new FileReader();
    reader.onload = async (e) => {
      // 异步执行
      var data = e.target.result;
      let wb = window.XLSX.read(data, {
        type: "binary",
      });
      let worksheet = JSON.stringify(
        window.XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
      );
      console.log(worksheet);
      let worksheetarr = JSON.parse(worksheet);
      let kjhsd = [];
      const lijne = [];
      worksheetarr.map((a) => {
        let obj = {
          addTime: transferTimeYMDHm(),
          ...ew,
        };
        for (let key in a) {
          jhbjhwe.map((b) => {
            if (b.title == key && a[key] !== undefined) {
              obj[b.key] = a[key];
            }
          });
        }
        for (let key in obj) {
          jhbjhwe.map((b) => {
            if (!obj[b.key]) {
              obj[b.key] = "--";
            }
          });
        }
        if (ewcsobj) {
          obj = {
            ...obj,
            ...ewcsobj
          }
        }
        lijne.push(obj);
      });

      if (lijne.length <= 0) {
        window.$message.error(
          drerrtext || "导入模板内容不能为空，请修改后重试！"
        );
        return;
      }
      console.log(lijne);
      console.log('66666');
      const { errno }: any = await dxpost("kx/bulkImport", {
        list: JSON.stringify(lijne),
        name,
        sjname
      });
      if (errno == 0) {
        window.$message.success("导入成功！");
        resolve(true);
      } else {
        window.$message.error("导入失败！");
        resolve(false);
      }
    };
    reader.readAsBinaryString(file);
  });
};

export const dxdownFile = (href, fileName) => {
  let aLink = document.createElement("a");
  aLink.style.display = "none";
  aLink.href = href;
  aLink.download = fileName;
  // 触发点击-然后移除
  document.body.appendChild(aLink);
  aLink.click();
  document.body.removeChild(aLink);
};



export const TreeMenudx = (data) => {
  const arrData = []
  data.map(a => {
    if (!a.parentMenuCode) {
      a.children = []
      a.numer = 1
      arrData.push(a)
    }
  })
  data.map(a => {
    arrData.map(b => {
      if (a.parentMenuCode == b.id) {
        a.children = []
        a.numer = 2
        b.children.push(a)
      }
    })
  })

  data.map(a => {
    arrData.map(b => {
      b.children.map(c => {
        if (a.parentMenuCode == c.id) {
          a.isth = true
          a.numer = 3
          c.children.push(a)
        }
      })
    })
  })
  return arrData
}

export const jCode = function (value) {
  value = 'phone123456789' + value
  var keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678";
  var kleng = keys.length;
  var kstr = keys.split("");
  var v = "", cat, cat1, cat2, cat3;
  for (var i = 0; i < value.length; i++) {
    cat = value.charCodeAt(i);
    cat1 = cat % kleng;
    cat = (cat - cat1) / kleng;
    cat2 = cat % kleng;
    cat = (cat - cat2) / kleng;
    cat3 = cat % kleng;
    v += kstr[cat3] + kstr[cat2] + kstr[cat1];
  }
  return v;
}
export const zCode = function (value) {
  var keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678";
  var kleng = keys.length;
  var alen, cat1, cat2, cat3, num = 0, arr;
  arr = new Array(Math.floor(value.length / 3));
  alen = arr.length;
  for (var i = 0; i < alen; i++) {
    cat1 = keys.indexOf(value.charAt(num));
    num++;
    cat2 = keys.indexOf(value.charAt(num));
    num++;
    cat3 = keys.indexOf(value.charAt(num));
    num++;
    arr[i] = cat1 * kleng * kleng + cat2 * kleng + cat3
  }
  alen = eval("String.fromCharCode(" + arr.join(',') + ")");
  alen = alen.split('phone123456789')[1]
  return alen;
}



var tmpDown; //导出的二进制对象
export const downloadExl = (json, type?, name?) => {
  //根据json数据，获取excel的第一行(例如:姓名、年龄、性别)存至map
  var tmpdata = json[0];
  json.unshift({});
  var keyMap = []; //获取keys
  for (var k in tmpdata) {
    keyMap.push(k);
    json[0][k] = k;
  }
  tmpdata = [];
  json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
    v: v[k],
    position: (j > 25 ? getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
  }))).reduce((prev, next) => prev.concat(next)).forEach((v, i) => tmpdata[v.position] = {
    v: v.v
  });
  //设置区域,比如表格从A1到D10
  var outputPos = Object.keys(tmpdata);
  var tmpWB = {
    SheetNames: [], //保存的表标题
    Sheets: {}
  };
  var sheetName = '保存的sheet名字';
  tmpWB.SheetNames.push(sheetName);
  tmpWB.Sheets[sheetName] = Object.assign({},
    tmpdata, //内容
    { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] }//设置填充区域
  );
  //创建二进制对象写入转换好的字节流
  tmpDown = new Blob([s2ab(window.XLSX.write(tmpWB,
    { bookType: (type == undefined ? 'xlsx' : type), bookSST: false, type: 'binary' }//这里的数据是用来定义导出的格式类型
  ))], {
    type: ""
  });
  var href = URL.createObjectURL(tmpDown); //创建对象超链接
  var aLink = document.createElement('a');
  aLink.href = href;//绑定a标签
  aLink.download = name + '.xlsx';
  aLink.click();//模拟点击实现下载
  setTimeout(function () { //延时释放
    URL.revokeObjectURL(tmpDown); //用URL.revokeObjectURL()来释放这个object URL
  }, 100);
}
//字符串转字符流
function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}
//将指定的自然数转换为26进制表示。映射关系：[0-25] -> [A-Z]。
function getCharCol(n) {
  let temCol = '',
    s = '',
    m = 0
  while (n > 0) {
    m = n % 26 + 1
    s = String.fromCharCode(m + 64) + s
    n = (n - m) / 26
  }
  return s
}
// end




export const download = (url, filename) => {
  getBlob(url, (blob) => {
    saveAs(blob, filename);
  });
}

const getBlob = (url, cb) => {
  let xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob';
  xhr.onload = function () {
    if (xhr.status === 200) {
      cb(xhr.response);
    }
  };
  xhr.send();
}
const saveAs = (blob, filename) => {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    let link = document.createElement('a');
    let body = document.querySelector('body');
    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    // fix Firefox
    link.style.display = 'none';
    body.appendChild(link);
    link.click();
    body.removeChild(link);
    window.URL.revokeObjectURL(link.href);
  };

}


// 下载图片
export const downImg = (data, fileName, gs?) => {
  axios({
    method: 'get',
    url: data, // 图片的URL
    responseType: 'blob'
  }).then(res => {
    let url = window.URL.createObjectURL(new Blob([res.data]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName + (gs || '.jpg')) // 下载的文件名
    document.body.appendChild(link)
    link.click()
  })
}
// 下载二维码图片
export const downImgqr = (data, fileName, gs?) => {
  let url = window.URL.createObjectURL(data)
  let link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', fileName + (gs || '.jpg')) // 下载的文件名
  document.body.appendChild(link)
  link.click()
}
export const dxwarning = (content) => {
  return new Promise(function (resolve) {
    window.$useDialog.warning({
      title: "警告",
      content,
      positiveText: "确定",
      negativeText: "取消",
      onPositiveClick: async () => {
        resolve(1)
      },
    });
  })
}


export const ninsd = (dayxee, data) => {
  try {
    let jcxcert = []
    dayxee.map(a => {
      try {
        if (Array.isArray(data)) {
          data.map(b => {
            if (a.value == b) {
              jcxcert.push(a.label)
            }
          })
        } else {
          data.split(",").map(b => {
            if (a.value == b) {
              jcxcert.push(a.label)
            }
          })
        }

      } catch (e) {

      }
    })
    return jcxcert.join(",")
  } catch (e) {
    return '--'
  }
}